package com.company.transmqtt.config;

import com.company.transmqtt.service.MqttForwardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;

@Configuration
public class IntegrationConfig {

    @Autowired
    @Qualifier("sourceMqttClientFactory")
    private MqttPahoClientFactory sourceClientFactory;

    @Autowired
    @Qualifier("sourceClientId")
    private String sourceClientId;

    @Autowired
    private MqttForwardService mqttForwardService;

    // 输入消息通道
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    // MQTT消息驱动通道适配器（用于接收消息）
    @Bean
    public MqttPahoMessageDrivenChannelAdapter mqttInbound() {
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                sourceClientId + "-inbound", sourceClientFactory, mqttForwardService.getSourceTopics().toArray(new String[0]));
        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setOutputChannel(mqttInputChannel());
        adapter.setQos(1);
        
        // 添加连接状态监听 - 通过重写适配器的方法
        // 连接状态变化会通过Spring Integration的日志系统输出
        
        return adapter;
    }

    // 集成流：将接收到的消息交给转发服务处理
    @Bean
    public IntegrationFlow mqttInFlow() {
        return IntegrationFlows.from(mqttInputChannel())
                .handle(mqttForwardService.getSourceMessageHandler())
                .get();
    }
}